﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using LibrarySync2.Settings;
using System.IO;
using LibrarySync2.Common.Xml;
using LibrarySync2.Business.FileSystem;
using LibrarySync2.ChildForms;

namespace LibrarySync2.Controls
{
    public partial class ucManageBlacklistFile : BaseUserControl
    {
        public ucManageBlacklistFile()
        {
            InitializeComponent();
            LoadPreferences();
            UserPreferencesManager.PreferencesUpdated += new EventHandler<EventArgs>(UserPreferencesManager_PreferencesUpdated);
        }

        protected void UserPreferencesManager_PreferencesUpdated(object sender, EventArgs e)
        {
            LoadPreferences();
        }

        private void LoadPreferences()
        {
            libraryFileSelector.Path = UserPreferencesManager.Settings.DefaultLibraryFilePath;
            blacklistFileSelector.Path = UserPreferencesManager.Settings.DefaultBlacklistFilePath;
        }

        private void btnEditBlacklist_Click(object sender, EventArgs e)
        {
            var localLibraryFilePath = libraryFileSelector.Path;
           

            var localLibraryFile = new FileInfo(localLibraryFilePath);
            var localLibrary = (localLibraryFile != null && localLibraryFile.Exists) ?
               localLibraryFile.LoadSerializedContent<Library>() : null;

            var blacklistFilePath = blacklistFileSelector.Path;
            if (string.IsNullOrEmpty(blacklistFilePath))
            {
                this.ShowErrorMessage("You must select a blacklist file.");
                return;
            }
                
            var blacklistFile = new FileInfo(blacklistFilePath);

            var partnerLibraryFilePath = partnerLibraryFileSelector.Path;
            FileInfo partnerLibraryFile = null;
            if (!string.IsNullOrEmpty(partnerLibraryFilePath))
            {
                partnerLibraryFile = new FileInfo(partnerLibraryFilePath);
            }

            var blacklist = blacklistFile.Exists ? blacklistFile.LoadSerializedContent<Blacklist>() : new Blacklist();
            var partnerLibrary = (partnerLibraryFile != null && partnerLibraryFile.Exists) ?
                partnerLibraryFile.LoadSerializedContent<Library>() : null;



            var manageBlacklistForm = new ManageBlacklistForm(blacklist, partnerLibrary,localLibrary);
            var dialogResults = manageBlacklistForm.ShowDialog(this);

            if (dialogResults == DialogResult.OK)
            {
                blacklist = manageBlacklistForm.Blacklist;
                blacklist.Serialize(blacklistFile);
                ShowMessage("Blacklist file updated.");
            }
        }
    }
}
